﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using CUISample.Entity;
using System.Data.Linq;

namespace CUISample.Data
{
    /// <summary>
    /// User数据访问对象。
    /// </summary>
    public static class UserDAO
    {
        static SQLiteDataContext _UserDataContext = new SQLiteDataContext(new SQLiteConnection("Data Source=mydb.db;Version=3;"));

        /// <summary>
        /// 得到所有用户列表。
        /// </summary>
        /// <returns>用户列表</returns>
        public static List<User> GetAllUsers()
        {
            return _UserDataContext.UserTable.ToList();
        }

        /// <summary>
        /// 添加一个用户。
        /// </summary>
        /// <param name="user">用户对象</param>
        public static void InsertUser(User user)
        {
            // 重载批量添加方法。
            InserUsers(user);
        }

        /// <summary>
        /// 添加一组用户。
        /// </summary>
        /// <param name="users">用户对象数组</param>
        public static void InserUsers(params User[] users)
        {
            _UserDataContext.UserTable.InsertAllOnSubmit(users);
            _UserDataContext.SubmitChanges();
        }

        /// <summary>
        /// 根据ID进行批量或单个的更新。
        /// </summary>
        /// <param name="id">查找ID</param>
        /// <param name="user">修改User实例</param>
        public static void UpdateUsers(long id, User user)
        {
            _UserDataContext.UserTable
                .Where(i => i.ID == id)
                .ToList()
                .ForEach(i => i.Username = user.Username);
            
            _UserDataContext.SubmitChanges();
        }

        /// <summary>
        /// 根据用户名批量或单个删除用户。
        /// </summary>
        /// <param name="username">用户名</param>
        public static void DeleteUsers(string username)
        {
            _UserDataContext.UserTable.DeleteAllOnSubmit(_UserDataContext.UserTable.Where(i => i.Username == username));
            _UserDataContext.SubmitChanges();
        }
    }
}
